import {
  SVAE_CURRENT_SONG,
  SVAE_CURRENT_SONG_INDEX,
  SVAE_PLAYLIST,
  SEQUENCE
} from './constant'
import {
  getSongDetail
} from '@/network/player'


export const currentSongAction = (currentSong) => ({
  type: SVAE_CURRENT_SONG,
  currentSong
})

export const playListAction = (playList) => ({
  type: SVAE_PLAYLIST,
  playList
})

export const currentSongIndexAction = (currentSongIndex) => ({
  type: SVAE_CURRENT_SONG_INDEX,
  currentSongIndex
})

// 是派发是哪一种播放顺序 ：循环，随机，单击
export const sequenceAction = (sequence) => ({
  type: SEQUENCE,
  sequence
})

export const changeCurrentSong = (tag) => {
  return (dispatch, getState) => {
    const playList = getState().getIn(["player", "playList"]);
    const sequence = getState().getIn(["player", "sequence"]);
    let currentSongIndex = getState().getIn(["player", "currentSongIndex"]);

    switch (sequence) {
      case 1: // 随机播放
        let randomIndex = Math.floor(Math.random() * playList.length)
        while (randomIndex === currentSongIndex) {
          randomIndex = Math.floor(Math.random() * playList.length)
        }
        currentSongIndex = randomIndex;
        break;
      default: // 顺序播放
        currentSongIndex += tag;
        if (currentSongIndex >= playList.length) currentSongIndex = 0;
        if (currentSongIndex < 0) currentSongIndex = playList.length - 1;
    }

    const currentSong = playList[currentSongIndex];
    dispatch(currentSongAction(currentSong));
    dispatch(currentSongIndexAction(currentSongIndex));
  }
}

export const getSongDetailAction = (ids) => {
  return async (dispatch, getState) => {

    // 1.根据id查找playList中是否已经有了该歌曲
    const playList = getState().getIn(['player', 'playList'])
    const songIndex = playList.findIndex((song) => song.id === ids)

    if (songIndex !== -1) {
      // 查找歌曲
      dispatch(currentSongIndexAction(songIndex))
      const song = playList[songIndex]
      dispatch(currentSongAction(song))
    } else {
      // 没找到歌曲  发请求
      const res = await getSongDetail(ids)
      const song = (res.songs && res.songs[0])
      if (!song) return;

      // 1.将最新请求到的数据添加到播放列表中
      const newPlayList = [...playList]
      newPlayList.push(song)

      // 2.更新redux中的值
      dispatch(playListAction(newPlayList))
      dispatch(currentSongIndexAction(newPlayList.length - 1))
      dispatch(currentSongAction(song))


    }
  }
}